package com.bootdo.common.utils;


import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: 况鑫威
 * @Date: 2021/4/23
 * @Time: 14:55
 * @ClassName: getAge
 * @Description: com.dlit.logic.utils
 */
public class ConversionUtil {
    /**
     * 功能描述: 获取access_token
     * @Param: [wxCode]
     * @Return: java.util.Map<java.lang.String,java.lang.Object>
     * @Author: 况鑫威
     * @Date: 2021/6/11
     * @Time: 11:01
     */
    public static String getAccessToken(String appId, String appSecret) {
        /**
         * wxCode:用户登录时获取的code
         * appid：小程序的Appid
         * appid：小程序的秘钥
         */
        String host = "https://api.weixin.qq.com";
        String path = "/cgi-bin/token";
        //把数据放入请求体中
        HashMap<String, String> body = new HashMap<>();
        body.put("appid", appId);
        body.put("secret", appSecret);
        body.put("grant_type", "client_credential");
        String data = "";
        try {
            //获取获取access_token
            HttpResponse response = HttpUtils.doGet(host, path, "GET", new HashMap<String, String>(), body);
            //json数据
            data = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.parseObject(data, Map.class).get("access_token").toString();
    }
    /**
     * 功能描述: 获取access_token
     * @Param: [wxCode]
     * @Return: java.util.Map<java.lang.String,java.lang.Object>
     * @Author: 况鑫威
     * @Date: 2021/6/11
     * @Time: 11:01
     */
    public static String getQRCode(String access_token, String scene) {
        /**
         * wxCode:用户登录时获取的code
         * appid：小程序的Appid
         * appid：小程序的秘钥
         */
        String host = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
        //把数据放入请求体中
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        HashMap<String, String> body = new HashMap<>();
        body.put("access_token", access_token);
        body.put("scene", scene);
        RestTemplate rest = new RestTemplate();

        try {

            HttpEntity requestEntity = new org.springframework.http.HttpEntity(body, headers);
            ResponseEntity<byte[]> entity = rest.exchange(host, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);

            System.out.println("调用小程序生成微信永久二维码URL接口返回结果:" + entity.getBody());
            byte[] res = entity.getBody();
            return Base64.encodeBase64String(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 功能描述: 处理图片路径
     *
     * @Param: [fileName, Ip]
     * @Return: java.lang.String
     * @Author: 况鑫威
     * @Date: 2021/6/1
     * @Time: 15:12
     */
    public static String dealWithUrl(String fileName, String Ip) {
        if (fileName != null && !fileName.equals("")) {
            return Ip + "/upload/" + fileName;
        }
        return null;
    }

    public static Long TimedTask(Date date) {

        //获取今天时间
        Calendar cl1 = Calendar.getInstance();
        cl1.setTime(new Date());

        //结束时间
        Calendar cl2 = Calendar.getInstance();
        cl2.setTime(date);

        int day = cl2.get(Calendar.DATE) - cl1.get(Calendar.DATE);
        if(day < 0){
            throw new RuntimeException("面试时间不能再当前时间或当前时间之前");
        }
        int hour = cl2.get(Calendar.HOUR) - cl1.get(Calendar.HOUR);
        if(day == 0 && hour < 0){
            throw new RuntimeException("面试时间不能再当前时间或当前时间之前");
        }
        int minute = cl2.get(Calendar.MINUTE) - cl1.get(Calendar.MINUTE);
        if(day == 0 && hour == 0 && minute < 0){
            throw new RuntimeException("面试时间不能再当前时间或当前时间之前");
        }
        //全部转化为分钟
        long endMinute = day * 24 * 60 + hour * 60 + minute;

        return endMinute;
    }

    /**
     * 功能描述: 通过生日获取年龄
     * @Param: [birthday]
     * @Return: java.lang.Integer
     * @Author: 况鑫威
     * @Date: 2021/4/23
     * @Time: 14:58
     */
    public static Integer getAge(String birthday){
        if(birthday == null || birthday.equals("")){
            return 0;
        }
        Integer workExperience = 0;
        Calendar cl2 = Calendar.getInstance();
        try {
            //获取今天时间
            Calendar cl1 = Calendar.getInstance();
            cl1.setTime(new Date());
            int nowYear = cl1.get(Calendar.YEAR);
            int nowMonth = cl1.get(Calendar.MONTH);

            //转换开始时间
            Date date1 = new SimpleDateFormat("yyyy-MM").parse(birthday);
            cl2.setTime(date1);
            int yearStartDate = cl2.get(Calendar.YEAR);
            int monthStartDate = cl2.get(Calendar.MONTH);

            if(nowYear - yearStartDate <= 0){
                return 0;
            }else{
                if(nowMonth - monthStartDate < 0){
                    workExperience = nowYear - yearStartDate - 1;
                } else {
                    workExperience = nowYear - yearStartDate;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return workExperience;
    }

    //工作经验转换
    public static Integer workExperience(String attendWorkTime){

        Integer workExperience = 0;
        Calendar cl2 = Calendar.getInstance();
        try {
            if(attendWorkTime != null && !attendWorkTime.equals("")){
                //获取今天时间
                Calendar cl1 = Calendar.getInstance();
                cl1.setTime(new Date());
                int nowYear = cl1.get(Calendar.YEAR);
                int nowMonth = cl1.get(Calendar.MONTH);

                //转换开始时间
                Date date1 = new SimpleDateFormat("yyyy-MM").parse(attendWorkTime);
                cl2.setTime(date1);
                int yearStartDate = cl2.get(Calendar.YEAR);
                int monthStartDate = cl2.get(Calendar.MONTH);

                if(nowYear - yearStartDate <= 0){
                    return 0;
                }else{
                    if(nowMonth - monthStartDate < 0){
                        workExperience = nowYear - yearStartDate - 1;
                    } else {
                        workExperience = nowYear - yearStartDate;
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return workExperience;
    }

    /**
     * 功能描述: 集合分页
     *
     * @Param: [list, page, rows]
     * @Return: java.util.List
     * @Author: 况鑫威
     * @Date: 2021/6/1
     * @Time: 15:13
     */
    public static List pageList(List list, Integer page, Integer rows) {
        int limit = rows * (page - 1);
        int size = rows * page;
        if (list.size() > limit) {
            if (list.size() <= size) {
                size = list.size();
            }
            list = list.subList(limit, size);
            return list;
        }
        return new ArrayList();
    }

    /**
     * description Map的value值降序排序
     *
     * @param map
     * @return java.util.Map
     * @version 1.0
     * @date 2020/12/12 17:48
     */
    public static Map sortMap(Map<String, Integer> map, Integer num) {

        //获取entrySet
        Set<Map.Entry<String, Integer>> mapEntries = map.entrySet();

        //使用链表来对集合进行排序，使用LinkedList，利于插入元素
        List<Map.Entry<String, Integer>> result = new LinkedList<>(mapEntries);
        //自定义比较器来比较链表中的元素
        Collections.sort(result, new Comparator<Map.Entry<String, Integer>>() {
            //基于entry的值（Entry.getValue()），来排序链表
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        //将排好序的存入到LinkedHashMap(可保持顺序)中，需要存储键和值信息对到新的映射中。
        Integer sort = 1;
        Map<String, Integer> linkMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> newEntry : result) {
            // 取出排名前5的值
            if (sort <= num) {
                linkMap.put(newEntry.getKey(), newEntry.getValue());
                ++sort;
            }
        }
        return linkMap;
    }

    public static String pathLastOf(String path){
        if(path != null && path.lastIndexOf("/") != -1){
            path = path.substring(path.lastIndexOf("/")+1);
        }
        return path;
    }


    //把两个数字之间的值获取成数字
    public static String[] dateConversion(Integer a, Integer b){
        String[] s = new String[a - b + 1];
        for (int i = 0; i < s.length; i++){
            s[i] = ""+a+1;
            a = a+1;
        }
        return s;
    }

}
